package com.hogocloud.corelibrary.base

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.Nullable
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProviders
import com.hogocloud.corelibrary.R
import com.hogocloud.corelibrary.common.dialog.LoadingDialog
import com.hogocloud.corelibrary.common.manager.AppManager
import com.hogocloud.corelibrary.common.rxbus.RxBus
import com.hogocloud.corelibrary.common.transitionmode.TransitionMode
import com.hogocloud.corelibrary.utils.StatusBarUtils
import kotlinx.android.synthetic.main.fragment_base.*
import kotlinx.android.synthetic.main.layout_common_toolbar.*

/**
 * base activity
 *
 * @author gjc
 * @version 1.0.0
 * @since 2019-08-04
 */
abstract class BaseActivity() : AppCompatActivity(), IBaseViewModelEventObserver {


    companion object {
        private var mLoadingView: LoadingDialog? = null
    }

    protected var mTransitionMode: TransitionMode = TransitionMode.RIGHT
    protected lateinit var mLeftButton: ImageView
    protected lateinit var mBtnToolbarRight: TextView
    protected lateinit var mTvToolbarRight: TextView
    protected lateinit var mIvToolbarRight: ImageView
    protected lateinit var mContext: Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //设置系统状态栏透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        }
        //设置状态栏为light模式，文字颜色为黑色
        StatusBarUtils.setLightMode(this)
        //自定义堆栈管理
        AppManager.addActivity(this)
        setContentView(R.layout.fragment_base)
        mContext = this

        val contentView = layoutInflater.inflate(initLayout(), null)
        fl_container.addView(contentView)
        initView(savedInstanceState)
        initViewModelEvent()

        //activity 转场方式
        when (setOverridePendingTransitionMode(mTransitionMode)) {
            TransitionMode.LEFT -> overridePendingTransition(R.anim.left_in, R.anim.left_out)
            TransitionMode.RIGHT -> overridePendingTransition(R.anim.enter_trans, R.anim.exit_right)
            TransitionMode.TOP -> overridePendingTransition(R.anim.top_in, R.anim.top_out)
            TransitionMode.BOTTOM -> overridePendingTransition(R.anim.bottom_in, 0)
            TransitionMode.SCALE -> overridePendingTransition(R.anim.scale_in, R.anim.scale_out)
            TransitionMode.FADE -> overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
            TransitionMode.ZOOM -> overridePendingTransition(R.anim.zoomin, R.anim.zoomout)
        }
    }

    /**
     * 初始化布局
     */
    abstract fun initLayout(): Int

    /**
     * 初始化布局组建
     */
    abstract fun initView(savedInstanceState: Bundle?)

    override fun getLifecycleOwner(): LifecycleOwner = this

    /**
     * 初始化toolbar
     * 只要调用该方法， toolbar就会显示，
     * 右边文字或者按钮需要单独设置显示状态
     */
    fun initTitle(@StringRes title: Int) {
        layout_title.visibility = View.VISIBLE
        tv_toolbar_title.text = getString(title)
        mLeftButton = iv_act_back
        mTvToolbarRight = tv_toolbar_right
        mBtnToolbarRight = btn_toolbar_right
        mIvToolbarRight = iv_toolbar_right
        iv_act_back.setOnClickListener { onBackPressed() }
    }

    /**
     * 初始化toolbar
     * 只要调用该方法， toolbar就会显示，
     * 右边文字或者按钮需要单独设置显示状态
     */
    fun initTitle(title: String) {
        layout_title.visibility = View.VISIBLE
        tv_toolbar_title.text = title
        mLeftButton = iv_act_back
        mTvToolbarRight = tv_toolbar_right
        mBtnToolbarRight = btn_toolbar_right
        mIvToolbarRight = iv_toolbar_right
        iv_act_back.setOnClickListener { onBackPressed() }
    }

    fun <T : BaseViewModel> getViewModel(clazz: Class<T>) =
        ViewModelProviders.of(this).get(clazz)

    /**
     * 显示加载框
     */
    override fun showLoading(@Nullable msg: String) {
        mLoadingView = LoadingDialog.Builder(this)
            .setCancelOutside(false)
            .setCancelable(true)
            .setMessage(msg)
            .create()
        mLoadingView?.show()
    }

    /**
     * 消失加载框
     */
    override fun hideLoading() {
        mLoadingView?.dismiss()
    }

    /**
     * 加载错误布局
     */
    override fun stateError() {

    }

    /**
     * 无网络布局
     */
    override fun stateNoNetWork() {

    }

    /**
     * 空页面
     */
    override fun stateEmpty() {

    }

    /**
     * 页面加载中布局（和showLoading使用其一）
     */
    override fun stateLoading() {

    }

    /**
     * 显示内容页面
     */
    override fun stateMain() {

    }

    /**
     * 隐藏键盘
     *
     * @return 隐藏键盘结果
     *
     *
     * true:隐藏成功
     *
     *
     * false:隐藏失败
     */
    protected fun hiddenKeyboard(): Boolean {
        //点击空白位置 隐藏软键盘
        try {
            val mInputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            return mInputMethodManager.hideSoftInputFromWindow(
                this
                    .currentFocus!!.windowToken, 0
            )
        } catch (e: Exception) {
            return false
        }

    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN &&
            currentFocus != null &&
            currentFocus!!.windowToken != null
        ) {

            val v = currentFocus
            if (isShouldHideKeyboard(v, event)) {
                hiddenKeyboard()
            }
        }
        return super.dispatchTouchEvent(event)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationOnScreen(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return (event.rawX <= left || event.rawX >= right
                    || event.rawY <= top || event.rawY >= bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false
    }

    open fun getStatusBarHeight():Int{
        //适配状态栏高度
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    private fun setOverridePendingTransitionMode(transitionMode: TransitionMode): TransitionMode {
        mTransitionMode = transitionMode
        return mTransitionMode
    }

    override fun finish() {
        super.finish()
        when (setOverridePendingTransitionMode(mTransitionMode)) {
            TransitionMode.LEFT -> overridePendingTransition(R.anim.left_in, R.anim.left_out)
            TransitionMode.RIGHT -> overridePendingTransition(R.anim.exit_right, R.anim.exit_trans)
            TransitionMode.TOP -> overridePendingTransition(R.anim.top_in, R.anim.top_out)
            TransitionMode.BOTTOM -> overridePendingTransition(0, R.anim.bottom_out)
            TransitionMode.SCALE -> overridePendingTransition(R.anim.scale_in, R.anim.scale_out)
            TransitionMode.FADE -> overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
            TransitionMode.ZOOM -> overridePendingTransition(R.anim.zoomin, R.anim.zoomout)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppManager.finishActivity(this)
        RxBus.removeAllStickyEvents()
    }
}